package sjsu.android;


import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.chart.BarChart.Type;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer.Orientation;

import dbAdapter.CreateDailyInfoData;
import dbAdapter.DailyAllowance;
import dbAdapter.DailyInfoDBAdapter1;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Typeface;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.TwoLineListItem;
import android.widget.LinearLayout;
import android.os.Bundle;
import android.provider.MediaStore.Audio;
public class WeeklyReportActivity extends Activity {
	Date currDate = null;
	int dailyAllowance;
	//final int recDailyAllowance = 2000;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		DailyAllowance da = new DailyAllowance();
		dailyAllowance = da.getDailyAllowance(this);

		currDate = new java.sql.Date(System.currentTimeMillis());

		showReportInPortrait();
	}

	private void showReportInPortrait() {
		setContentView(R.layout.chart);
		CreateDailyInfoData data = new CreateDailyInfoData();
		data.create(this);
		ImageButton prevButton = (ImageButton) findViewById(R.id.previousButton);
		prevButton.setOnClickListener(new OnClickListener() {


			public void onClick(View v) {
				Date date = DailyInfoDBAdapter1.adjustDateToMonday(currDate);
				currDate = DailyInfoDBAdapter1.subtractSevenDays(date);

				showReportForDate(dailyAllowance,currDate);

			}
		});

		ImageButton nextButton = (ImageButton) findViewById(R.id.nextButton);
		nextButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Date date = DailyInfoDBAdapter1.adjustDateToMonday(currDate);
				currDate = DailyInfoDBAdapter1.addSevenDays(date);

				showReportForDate(dailyAllowance,currDate);

			}
		});
		showReportForDate(dailyAllowance, currDate);
	}

	private void showReportForDate(int recDailyAllowance, Date date) {
		TextView reportHeader = (TextView) findViewById(R.id.reportHeader);
		reportHeader.setText("Weekly Report");
		Date mondayDate = DailyInfoDBAdapter1.adjustDateToMonday(date);
		TextView monthText = (TextView) findViewById(R.id.MonthDisplayTextView);
		SimpleDateFormat sdf = new SimpleDateFormat("MMM d yyyy");
		monthText.setText("Week Of " + sdf.format(mondayDate));
		DailyInfoDBAdapter1 db = new DailyInfoDBAdapter1(this);
		db.open();
		HashMap<String, Integer> caloriesConsumedMap =(HashMap<String, Integer>) db.getCaloriesConsumedForWeek(date);
		//HashMap<Integer, Integer> caloriesBurntMap =(HashMap<Integer, Integer>) db.getCaloriesBurntForMonth(date.getMonth() + 1, date.getYear() + 1900);


		int numDaysAboveDailyAllowance = getNumberOfDaysAboveDailyAllowance(caloriesConsumedMap, recDailyAllowance);
		int avgCaloriesConsumed = getAvgCaloriesConsumed(caloriesConsumedMap);
		//int avgCaloriesBurnt = getAvgCaloriesBurnt(caloriesBurntMap);
		final GraphicalView mChartView = getGraphView(recDailyAllowance, caloriesConsumedMap);

		//Intent chartIntent = ChartFactory.getLineChartIntent(this, xyMultipleSeriesDataset, xyMultipleSeriesRenderer);
		//startActivity(chartIntent);
		LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
		layout.removeAllViews();

		layout.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT));
		mChartView.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				/*
				WeeklyReportActivity.this.setContentView(R.layout.chart_landscape);
				 GraphicalView mChartView = ChartFactory.getBarChartView(WeeklyReportActivity.this, xyMultipleSeriesDataset, xyMultipleSeriesRenderer, Type.DEFAULT);
				LinearLayout layout = (LinearLayout) findViewById(R.id.chart_landscape);
				layout.removeAllViews();
				layout.addView(mChartView, new LayoutParams(LayoutParams.FILL_PARENT,
						LayoutParams.FILL_PARENT));
				//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
				 */


			}});


		/*
		WebView webView = (WebView) findViewById(R.id.WebView01);
		//String mUrl = "http://chart.apis.google.com/chart?cht=p3&chd=t:30,60,10&chs=250x100&chl=cars|bikes|trucks";
		String mUrl = "http://chart.apis.google.com/";
		webView.loadUrl(mUrl);
		 */
		TextView numTextView = (TextView) findViewById(R.id.valueNumDaysAboveDailyAllowance);
		numTextView.setText(""+numDaysAboveDailyAllowance);

		TextView avgCaloriesConsumedTextView = (TextView) findViewById(R.id.valueAvgCaloriesConsumed);
		avgCaloriesConsumedTextView.setText( ""+ avgCaloriesConsumed);

		TextView avgCaloriesBurntTextView = (TextView) findViewById(R.id.avgCaloriesBurntTextView);
		avgCaloriesBurntTextView.setVisibility(View.INVISIBLE);
		//avgCaloriesBurntTextView.setText("Average calories Burnt:" + avgCaloriesBurnt);

		TextView valueAvgCaloriesBurntTextView = (TextView) findViewById(R.id.valueAvgCaloriesBurnt);
		valueAvgCaloriesBurntTextView.setVisibility(View.INVISIBLE);

	}

	private GraphicalView getGraphView(int recDailyAllowance,
			HashMap<String, Integer> caloriesConsumedMap) {
		int minCaloriesforYaxis = 0;
		int maxCaloriesforYaxis = getMaximumCaloriesforYaxes(caloriesConsumedMap, recDailyAllowance) + 50;
		XYSeries data1 = new XYSeries("Calories Consumed");
		XYSeries data2 = new XYSeries(" ");
		String[] days = new String[] {"Mon","Tue","Wed","Thu","Fri","Sat","Sun"};
		for(int i = 0; i<days.length; i++){
			Integer value = caloriesConsumedMap.get(days[i]);
			if (value!= null)
			{
				if(value>=dailyAllowance){
					data1.add(i, value);
					data2.add(i, dailyAllowance);
				}
				else
				{
					data1.add(i, value);
					data2.add(i, value);
				}
			}
			else
			{
				data1.add(i, 0);
				data2.add(i,0);
			}
		}


		final XYMultipleSeriesDataset xyMultipleSeriesDataset = new XYMultipleSeriesDataset();
		
		xyMultipleSeriesDataset.addSeries(data1);
		xyMultipleSeriesDataset.addSeries(data2);
		
		final XYMultipleSeriesRenderer xyMultipleSeriesRenderer = new XYMultipleSeriesRenderer();
		//xyMultipleSeriesRenderer.setChartTitle("Monthly Report");

		xyMultipleSeriesRenderer.setOrientation(Orientation.VERTICAL);
		//xyMultipleSeriesRenderer.addTextLabel(0, " ");
		for ( int i=0; i<days.length ; i++){
			xyMultipleSeriesRenderer.addTextLabel(i, days[i]);
		}
		xyMultipleSeriesRenderer.setAxesColor(Color.BLACK);
		xyMultipleSeriesRenderer.setLabelsColor(Color.BLACK);
		xyMultipleSeriesRenderer.setLabelsTextSize(12);
		xyMultipleSeriesRenderer.setAxisTitleTextSize(12);
		xyMultipleSeriesRenderer.setShowLegend(false);
		xyMultipleSeriesRenderer.setTextTypeface("sans_serif", Typeface.BOLD);

		xyMultipleSeriesRenderer.addTextLabel(7, "");
		xyMultipleSeriesRenderer.setChartValuesTextSize(12);
		xyMultipleSeriesRenderer.setXLabels(1);
		xyMultipleSeriesRenderer.setDisplayChartValues(false);
		xyMultipleSeriesRenderer.setBackgroundColor(Color.rgb(0xf5, 0xf5, 0xf5));
		xyMultipleSeriesRenderer.setApplyBackgroundColor(true);
		//xyMultipleSeriesRenderer.setXTitle("Days");
		xyMultipleSeriesRenderer.setYTitle("Calories");
		xyMultipleSeriesRenderer.setYAxisMin(minCaloriesforYaxis);
		xyMultipleSeriesRenderer.setYAxisMax(maxCaloriesforYaxis);
		xyMultipleSeriesRenderer.setXAxisMin(0);
		xyMultipleSeriesRenderer.setXAxisMax(7);
		XYSeriesRenderer xySeriesRenderer1 = new XYSeriesRenderer();
		xySeriesRenderer1.setColor(Color.RED);
		xySeriesRenderer1.setPointStyle(PointStyle.DIAMOND);
		xySeriesRenderer1.setLineWidth(1000);
		xyMultipleSeriesRenderer.addSeriesRenderer(xySeriesRenderer1);
		XYSeriesRenderer xySeriesRenderer2 = new XYSeriesRenderer();
		xySeriesRenderer2.setColor(Color.rgb(0xad, 0xd8, 0xe6));
		xySeriesRenderer2.setPointStyle(PointStyle.DIAMOND);
		xySeriesRenderer2.setLineWidth(1000);
		xyMultipleSeriesRenderer.addSeriesRenderer(xySeriesRenderer2);
		
		
		final GraphicalView mChartView = ChartFactory.getBarChartView(this, xyMultipleSeriesDataset, xyMultipleSeriesRenderer, Type.STACKED);
		return mChartView;
	}
	/*
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
	    super.onConfigurationChanged(newConfig);

	    // Checks the orientation of the screen
	    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            setContentView(R.layout.chart_landscape);
	    	Date mondayDate = DailyInfoDBAdapter1.adjustDateToMonday(currDate);
	    	DailyInfoDBAdapter1 db = new DailyInfoDBAdapter1(this);
			db.open();
			HashMap<String, Integer> caloriesConsumedMap =(HashMap<String, Integer>) db.getCaloriesConsumedForWeek(mondayDate);
			GraphicalView graphView = getGraphView(recDailyAllowance, caloriesConsumedMap);
			LinearLayout layout = (LinearLayout) findViewById(R.id.chart_landscape);
			layout.removeAllViews();
			layout.addView(graphView, new LayoutParams(LayoutParams.FILL_PARENT,
					LayoutParams.FILL_PARENT));
	    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
	       showReportInPortrait();	
	    }
	}
	 */

	private int getAvgCaloriesBurnt(HashMap<Integer, Integer> caloriesBurntMap) {
		int total = 0;
		int size = caloriesBurntMap.size();
		int avg = 0;
		for(int calories : caloriesBurntMap.values()){
			total = total + calories;

		}
		if (size != 0){
			avg = total/size;
		}
		return avg;
	}

	private int getAvgCaloriesConsumed(
			HashMap<String, Integer> caloriesConsumedMap) {
		int total = 0;
		int size = caloriesConsumedMap.size();
		int avg = 0;
		for(int calories : caloriesConsumedMap.values()){
			total = total + calories;

		}
		if( size != 0)
		{	
			avg = total/size;
		}
		return avg;


	}

	private int getNumberOfDaysAboveDailyAllowance(
			HashMap<String, Integer> caloriesConsumedMap, int recDailyAllowance) {
		int numDaysAboveDailyAllowance = 0;
		for(int calories : caloriesConsumedMap.values()){
			if(calories > recDailyAllowance){
				numDaysAboveDailyAllowance++;
			}

		}
		// TODO Auto-generated method stub
		return numDaysAboveDailyAllowance;
	}

	private List<Integer> sort(Set<Integer> keySet) {
		// TODO Auto-generated method stub
		List<Integer> listSet = new ArrayList<Integer>(keySet);
		Collections.sort(listSet);
		return listSet;
	}

	private int getMaximumCaloriesforYaxes(HashMap<String,Integer> caloriesConsumedMap,
			int recDailyAllowance) {
		int maxCaloriesConsumed = Integer.MIN_VALUE;
		for (int calories : caloriesConsumedMap.values()){
			if ( calories > maxCaloriesConsumed)
				maxCaloriesConsumed = calories;

		}
		if (maxCaloriesConsumed > recDailyAllowance)
			return maxCaloriesConsumed;
		else
			return recDailyAllowance;


	}
}